package preorder
import (
    //"time"
	"strings"
	"errors"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

//可预约项目分类
type ResType struct {
	ResTypeId int64  `orm:"column(res_type_id);pk;auto" json:"res_type_id" form:"res_type_id"` 
	PartnerId int64  `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"` //
	StoreId   int64  `orm:"column(store_id)" json:"store_id" form:"store_id"`             /*店铺ID*/
    ParentId  int64  `orm:"column(parent_id);null" json:"parent_id" form:"parent_id"`     /*parent_id=0:一级类目*/
    Name      string `orm:"column(name);size(128);null" json:"name" form:"name"`          /*类型名称*/
    Lft       int32  `orm:"column(lft);null" json:"-"`       
    Rgt       int32  `orm:"column(rgt);null" json:"-"`       
    Level     int32  `orm:"column(level);null" json:"level"`                              /*类目层级*/
}

func init() {
	orm.RegisterModel(new(ResType))
}

func InitDefaultRootResType(partnerId, storeId int64){
    exist := existRootResType(partnerId)
    if !exist {
	    v := ResType{}
		v.PartnerId = partnerId
	    v.StoreId = storeId
		v.Name = "分类"
		v.ParentId = 0
	    v.Lft = 1
	    v.Rgt = 2
	    v.Level = 1
	    AddResType(&v)
	}
}

func existRootResType(partnerId int64) bool {
    o := models.GetDefaultDB()
	exist := o.QueryTable(new(ResType)).Filter("partner_id",partnerId).Filter("parent_id",0).Exist()
	return exist
}

func AddResType(m *ResType) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetResTypeById(id int64) (v *ResType, err error) {
	o := models.GetDefaultDB()
	v = &ResType{ResTypeId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func UpdateResTypeById(m *ResType) (err error) {
	o := models.GetDefaultDB()
	v := ResType{ResTypeId: m.ResTypeId}
	if err = o.Read(&v); err == nil {
		if _, err = o.Update(m); err == nil {
			return
		}
	}
	return
}

func DeleteResType(id int64) (err error) {
	o := models.GetDefaultDB()
	v := ResType{ResTypeId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return
		}
	}
	return
}

func GetAllResTypes(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*ResType, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ResType))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*ResType
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func BatchAddResType(m *ResType, parentLft int32) (id int64, err error) {
	o := models.GetDefaultDB()
	o.Begin()
	id, err = o.Insert(m)
	if err != nil {
		o.Rollback()
		return id, err	
	}
	var r orm.RawSeter
    r = o.Raw("UPDATE res_type SET rgt = rgt + 2 WHERE rgt > ?", parentLft)
	_, err = r.Exec()
	if err != nil {
		o.Rollback()
		return id, err	
	}
    r = o.Raw("UPDATE res_type SET lft = lft + 2 WHERE lft > ?", parentLft)
	_, err = r.Exec()
	if err != nil {
		o.Rollback()
		return id, err	
	}
	o.Commit()
	return id, nil
}

